<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, ref, unref, nextTick } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { ElTree, ElCheckboxGroup, ElCheckbox } from 'element-plus'
import { getMenuTreeListApi } from '@/api/system/menuApi'
import { filter, eachTree } from '@/utils/tree'
import { findIndex } from '@/utils'

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  }
})

const treeRef = ref<typeof ElTree>()

const formSchema = ref<FormSchema[]>([
  {
    field: 'name',
    label: '角色名',
    component: 'Input'
  },
  {
    field: 'status',
    label: '状态',
    component: 'Select',
    value: 1,
    componentProps: {
      options: [
        {
          label: '禁用',
          value: 0
        },
        {
          label: '启用',
          value: 1
        }
      ]
    }
  },
  {
    field: 'remark',
    label: '备注',
    component: 'Input'
  },
  {
    field: 'menus',
    label: '菜单',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="flex w-full">
                <div class="flex-1">
                  <ElTree
                    ref={treeRef}
                    show-checkbox
                    node-key="id"
                    highlight-current
                    check-strictly
                    expand-on-click-node={false}
                    data={treeData.value}
                    onNode-click={nodeClick}
                  >
                    {{
                      default: (data: any) => {
                        return <span>{data.data?.meta?.title}</span>
                      }
                    }}
                  </ElTree>
                </div>
                <div class="flex-1">
                  {unref(currentTreeData) && unref(currentTreeData)?.permission ? (
                    <ElCheckboxGroup v-model={unref(currentTreeData).meta.rolePermissionList}>
                      {unref(currentTreeData)?.permission.map((v: any) => {
                        return <ElCheckbox label={v.value}>{v.label}</ElCheckbox>
                      })}
                    </ElCheckboxGroup>
                  ) : null}
                </div>
              </div>
            </>
          )
        }
      }
    }
  }
])

const currentTreeData = ref()
const nodeClick = (treeData: any) => {
  currentTreeData.value = treeData
}

const rules = reactive({
  name: [required()],
  role: [required()],
  status: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const treeData = ref<any>([])
const getMenuList = async () => {
  const res: any = await getMenuTreeListApi()
  if (!res) {
    return
  }
  treeData.value = res.data
  await nextTick()
  if (!props.currentRow) {
    handlerPermissionOption(res.data)
    return
  }

  const checked: any[] = []
  eachTree(props.currentRow.menus, (v) => {
    v = {
      id: v
    }
    checked.push({
      id: v.id,
      permission: v.meta?.permission || []
    })
  })
  eachTree(treeData.value, (v) => {
    const index = findIndex(checked, (item) => {
      return item.id === v.id
    })
    if (index > -1) {
      const meta = { ...(v.meta || {}) }
      meta.permission = checked[index].permission
      v.meta = meta
    }
  })
  for (const item of checked) {
    unref(treeRef)?.setChecked(item.id, true, false)
  }
  unref(treeRef)?.setCheckedKeys(
    checked.map((v) => v.id),
    false
  )
}
getMenuList()

const handlerPermissionOption = (data: any[]) => {
  // 将每个权限选项设置为默认值
  const defaultPermission = ['add', 'detail', 'edit', 'del']

  eachTree(data, (item) => {
    item.meta.rolePermissionList = [...defaultPermission]
  })
}

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (!valid) {
    return
  }
  const formData = await getFormData()
  const checkedKeys = unref(treeRef)?.getCheckedKeys() || []

  /**
   * 所有选中的节点
   */
  const data = filter(unref(treeData), (item: any) => {
    return checkedKeys.includes(item.id)
  })

  // 记录id
  const idList: any[] = []
  // 记录权限
  const rolePermissionList: any = {}
  eachTree(data, (item: any) => {
    rolePermissionList[item.id] = item.meta.rolePermissionList
    idList.push(item.id)
  })

  formData.rolePermissionList = JSON.stringify(rolePermissionList)
  formData.menus = idList
  return formData
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
